package com.pc.admin.test.runnable;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 一个卖票的类
 */
class buyticket implements Runnable {
    //Reentrantlock:可重进锁
    private final ReentrantLock locks = new ReentrantLock();
    //票数
    int ticket = 10;

    @Override
    //重写的方法
    public void run() {
        while (true) {
            try {
                //开启一个锁        开启一个锁最好放在try语句
                locks.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticket--);
                } else {
                    System.out.println("你买的票已经被购完");
                    break;
                }
            } finally {
                //关闭一个锁
                locks.unlock();
            }
        }
    }
}
